package cn.jiedh.app.meiweidk;

import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.DownloadListener;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.umeng.analytics.MobclickAgent;

import org.xutils.ex.HttpException;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jiedh.app.meiweidk.Utils.tool.ActivityUtil;
import cn.jiedh.app.meiweidk.Utils.tool.HtmlUtil;
import cn.jiedh.app.meiweidk.Utils.tool.L;
import cn.jiedh.app.meiweidk.Utils.tool.MobileUtils;
import cn.jiedh.app.meiweidk.Utils.tool.PicUtils;
import cn.jiedh.app.meiweidk.Utils.tool.T;
import cn.jiedh.app.meiweidk.Utils.tool.TimeUtils;
import cn.jiedh.app.meiweidk.Utils.tool.UrlUtils;
import cn.jiedh.app.meiweidk.base.BaseActivity;
import cn.jiedh.app.meiweidk.entity.BannerEntity;
import cn.jiedh.app.meiweidk.loan.LoanDetailActivity;
import cn.jiedh.app.meiweidk.login.LoginActivity;
import cn.jiedh.app.meiweidk.network.ResponseFailure;
import cn.jiedh.app.meiweidk.network.ResponseSuccess;
import cn.jiedh.app.meiweidk.response.BaseResponse;
import cn.jiedh.app.meiweidk.runtimepermissions.PermissionHelper;

/**
 * @name：MyWebActivity
 * @author：
 * @phone： 13308334117
 * @createTime： 2017/3/17
 * @modifyTime： 2017/3/17
 * @explain：用于网页展示，和H5页面的交互
 */
public class MyWebActivity extends BaseActivity implements View.OnClickListener {
    private static final int PERMISSION_SHARE=8;//分享请求权限的code
    public static final int LOAN_DETAIL_RESULT = 3;//返回产品详情页的resultCode

    private ValueCallback<Uri> mUploadMessage_5_0_down;
    ValueCallback<Uri[]> mUploadMessage_5_0_up;
    Uri imageUri;
    public final static int FILECHOOSER_RESULTCODE = 1;//选择文件返回
    @BindView(R.id.web)
    WebView web;
    @BindView(R.id.bar_img_back)
    ImageView barImgBack;
    @BindView(R.id.bar_tv_close)
    TextView bar_tv_close;
    @BindView(R.id.bar_tv_title)
    TextView barTvTitle;
    @BindView(R.id.bar_img_more)
    ImageView bar_img_more;
    private String url;
    private int source;//来源，用于调用不同接口。1为banner过来，需要显示分享，2为其他；
    private int bannerId;//点击banner页的id,用于v1.4.1的活动，返回此页面时重新获取url
    private BannerEntity bannerEntity;
    String title;
    int type = -1;//0链接，1富文本(消息等跳过来)
    String content = "";//富文本信息
    public static int isActivityEntrance = 0;//是否为活动入口，1为活动入口
    private long pageFinishedTime = 0;//webView加载完成时间

    @Override
    protected int getLayoutView() {
        return R.layout.activity_web;
    }

    @Override
    protected void initView(View view) {
        isActivityEntrance = 1;
        Date date = new Date(System.currentTimeMillis());
        pageFinishedTime = date.getTime();
        web.getSettings().setJavaScriptEnabled(true);
        web.getSettings().setLoadWithOverviewMode(true);
        web.getSettings().setUseWideViewPort(true);
//        web.getSettings().setSupportZoom(false); // 支持缩放
//        web.getSettings().setBuiltInZoomControls(true); // 启用内置缩放装置
        web.getSettings().setDomStorageEnabled(true);
        web.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                // 监听下载功能，当用户点击下载链接的时候，直接调用系统的浏览器来下载
                Log.d("url--", url);
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });
        //设置Web视图
        web.setWebViewClient(new HelloWebViewClient());
        web.setWebChromeClient(new MyWebChromeClient());
        MobclickAgent.onEvent(this,"goingweb");
        bar_tv_close.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bar_img_more:
                showshear();
                break;
            case R.id.bar_tv_close:
                finish();
                break;
            default:
                break;
        }
    }

    private int handleDoSign = 1001;
    private int handleDoAuth = 1002;
    private int handleDate = 1003;

    @Override
    public void defaultRequestError(HttpException error, String msg) {
        dismissLoadingDialog();
        clearHistory();
    }


    //Web视图
    private class HelloWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            L.d("====>" + url);
            if (url == null) {
                return true;
            } else if (url != null && url.contains("tel:")) {//网页内拨打电话
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                return true;
            } else if (url.contains("type=xly_goLoan")) {//跳转到首页
                Intent intent = new Intent(MyWebActivity.this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                return true;
            } else if (url.contains("type=xly_toShare")) {//分享
                showshear();
                return true;
            } else if (url.startsWith("http") || url.startsWith("https")) {
                return super.shouldOverrideUrlLoading(view, url);
            } else if (url.contains("xly://handleDoSign")) {//点击登录
                ActivityUtil.next(MyWebActivity.this, LoginActivity.class, handleDoSign);
                return true;
            } else if (url.contains("xly://handleDoAuth")) {//点击实名
                /**
                 * 跳转到实名认证页面
                 */
//				ActivityUtil.next(MyWebActivity.this, LimitManagerActivity.class, handleDoAuth);
                return true;
            } else if (url.contains("xly://handleDate")) {//点击预约
                String params = url.substring(url.indexOf("?") + 1);
//				handleDate(params);
                return true;
            } else if (url.contains("xly://handleConsult")) {//点击在线客服
                String url11 = "mqqwpa://im/chat?chat_type=wpa&uin=1606421365&version=1";
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url11));
                List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent, 0);
                if (list.size() > 0) {
                    startActivity(intent);
                } else {
                    T.showShortToast("请您先安装QQ");
                }
                return true;
            } else {


                if (MobileUtils.isAppInstalled(MyWebActivity.this, MobileUtils.yyb)) {
                    try{
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        startActivity(intent);
                        return true;
                    }catch (Exception e){
                        return super.shouldOverrideUrlLoading(view, url);
                    }
                } else {
                    return super.shouldOverrideUrlLoading(view, url);
                }
            }
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            L.e("第三方产品的链接有ssl问题" + error.getUrl());
            handler.proceed(); // 接受信任所有网站的证书
        }
    }

    @Override
    protected void initData() {
        clearCacheFolder(this.getCacheDir(), System.currentTimeMillis());
        try {
            if (getIntent().getExtras() != null) {
                url = getIntent().getExtras().getString("url");
                L.d("url==="+url);
                bannerId = getIntent().getExtras().getInt("id");
                source = getIntent().getExtras().getInt("source");
                title = getIntent().getExtras().getString("title");
                type = getIntent().getExtras().getInt("type");
                content = getIntent().getExtras().getString("content");
                if (source == 1) {  //处理分享
                    bannerEntity = (BannerEntity) getIntent().getSerializableExtra("Hot");
                    bar_img_more.setVisibility(View.INVISIBLE);
                } else {
                    bar_img_more.setVisibility(View.INVISIBLE);
                }
                barTvTitle.setText(title);
                if (TextUtils.isEmpty(title)) {
                    title = getResources().getString(R.string.app_name);
                }
                if (!TextUtils.isEmpty(url)) {//兼容之前的版本
                    web.loadUrl(url);
                } else if (type == 1) {//富文本
                    web.loadData(content, HtmlUtil.MIME_TYPE, HtmlUtil.ENCODING);
                } else {
                    refresh();
                }
//                bar_img_more.setOnClickListener(this);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void refresh() {
        getInfo();
    }


    /**
     * 获取banner 详细信息
     */
    private void getInfo() {
        Map map = new HashMap<String, Objects>();
        map.put("bannerId", bannerId);

        request(this, UrlUtils.BANNERDETAIL, map, false, new ResponseSuccess<BannerEntity>() {
            @Override
            public void onRequestSucceed(BaseResponse<BannerEntity> response) {
                bannerEntity = response.getData();
                if (bannerEntity != null) {
                    if (!TextUtils.isEmpty(bannerEntity.getName())) {
                        barTvTitle.setText(bannerEntity.getName());
                    }
                    if (bannerEntity.getType() == 1) {//banner类型 0不可点击 1外链 2内链
                        if (!TextUtils.isEmpty(bannerEntity.getLink())) {
                            web.loadUrl(bannerEntity.getLink());
                        }
                    } else {
                        int inId = response.getData().getInId(); //内链的Id(例如内链的产品,就用这个ID去查产品详情),只有在type为2时返回
                        Bundle bundle = new Bundle();
                        bundle.putInt("productId", inId);
                        ActivityUtil.next(MyWebActivity.this, LoanDetailActivity.class, bundle);
                        MyWebActivity.this.finish();
                    }

                }
            }
        }, new ResponseFailure() {
            @Override
            public void onRequestFailure(HttpException error, String msg) {
                L.e("初始化banner错误" + msg);
                T.showShortToast(msg);
            }
        });
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        // android 7.0系统解决拍照的问题
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
            builder.detectFileUriExposure();
        }
    }

    @Override
    public void finish() {
        Intent intent = new Intent();
        if (pageFinishedTime == 0) {
            Date date = new Date(System.currentTimeMillis());
            pageFinishedTime = date.getTime();
        }
        intent.putExtra("time", TimeUtils.calculationRemainTime(pageFinishedTime, 3));
        setResult(LOAN_DETAIL_RESULT, intent);
        super.finish();
    }

    @OnClick(R.id.bar_img_back)
    public void onClick() {
        if (web.canGoBack()) {
            web.goBack(); // goBack()表示返回WebView的上一页面
            bar_tv_close.setVisibility(View.VISIBLE);
        } else {
            Intent intent = new Intent();
            if (pageFinishedTime == 0) {
                Date date = new Date(System.currentTimeMillis());
                pageFinishedTime = date.getTime();
            }
            intent.putExtra("time", TimeUtils.calculationRemainTime(pageFinishedTime, 3));
            setResult(LOAN_DETAIL_RESULT, intent);
            finish();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            if (web.canGoBack()) {
                web.goBack(); // goBack()表示返回WebView的上一页面
                bar_tv_close.setVisibility(View.VISIBLE);
                return true;
            }
            finish();
            clearCacheFolder(this.getCacheDir(), System.currentTimeMillis());
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (requestCode == FILECHOOSER_RESULTCODE || requestCode == 131073) {// 选择文件返回
            if (resultCode == RESULT_OK) {
                // 这个131073是在调试前面的项目中出现的bug
                // 在调用相册后requestCode的是131073，可根据调试情况修改或者删除
                if (null == mUploadMessage_5_0_down && mUploadMessage_5_0_up == null) {
                    return;
                }
                Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    onActivityResultAboveL(requestCode, resultCode, intent);
                } else {
                    String path = PicUtils.getPath(getApplicationContext(),
                            result);
                    Uri uri = Uri.fromFile(new File(path));
                    mUploadMessage_5_0_down.onReceiveValue(uri);
                    mUploadMessage_5_0_down = null;
                }
            } else {
                setDefault();
            }
        } else if (requestCode == handleDoSign) {//登录
            refresh();
        } else if (requestCode == handleDoAuth) {//实名
            refresh();
        } else if (requestCode == handleDate && resultCode == RESULT_OK) {//预约
            refresh();
        }
    }


    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @SuppressWarnings("null")
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {
        if (requestCode != FILECHOOSER_RESULTCODE
                || mUploadMessage_5_0_up == null) {
            return;
        }
        Uri[] results = null;
        if (resultCode == RESULT_OK) {
            if (data == null) {
                results = new Uri[]{imageUri};
            } else {
                String dataString = data.getDataString();
                ClipData clipData = data.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }
                if (dataString != null) {
                    results = new Uri[]{Uri.parse(dataString)};
                }
            }
        }
        if (results != null) {
            mUploadMessage_5_0_up.onReceiveValue(results);
            mUploadMessage_5_0_up = null;
        } else {
            results = new Uri[]{imageUri};
            mUploadMessage_5_0_up.onReceiveValue(results);
            mUploadMessage_5_0_up = null;
        }
        return;
    }

    /**
     * 获取图片设置默认值
     */
    void setDefault() {
        if (mUploadMessage_5_0_up != null) {
            mUploadMessage_5_0_up.onReceiveValue(null);
        }
        mUploadMessage_5_0_up = null;
        if (mUploadMessage_5_0_down != null) {
            mUploadMessage_5_0_down.onReceiveValue(null);
        }
        mUploadMessage_5_0_down = null;
    }

    private class MyWebChromeClient extends WebChromeClient {
        // 不可添加@Override

        // 解决file表单上传文件的问题
        // For Android 3.0+
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            mUploadMessage_5_0_down = uploadMsg;
            getPhoto();
        }

        // For Android 3.0+
        public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
            mUploadMessage_5_0_down = uploadMsg;
            getPhoto();
        }

        // For Android 4.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            mUploadMessage_5_0_down = uploadMsg;
            getPhoto();

        }

        // For Android 5.0+
        @Override
        @SuppressLint("NewApi")
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                                         FileChooserParams fileChooserParams) {
            if (mUploadMessage_5_0_up != null) {
                mUploadMessage_5_0_up.onReceiveValue(null);
            }
            mUploadMessage_5_0_up = filePathCallback;
            getPhoto();
            return true;
        }

        /**
         * 开启文件选择 5.0以下使用 此处使用系统调用的文件选择器 可以以使用自定义的或者是掉起相机拍照
         * 在onActivityResult返回成功后将获取 到的uri交给对应的ValueCallback处理
         */
        private void getPhoto() {
            File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MyApp");
            // Create the storage directory if it does not exist
            if (!imageStorageDir.exists()) {
                imageStorageDir.mkdirs();
            }
            File file = new File(imageStorageDir + File.separator + "IMG_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
            imageUri = Uri.fromFile(file);

            final List<Intent> cameraIntents = new ArrayList<>();
            final Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            final PackageManager packageManager = getPackageManager();
            final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
            for (ResolveInfo res : listCam) {
                final String packageName = res.activityInfo.packageName;
                final Intent i = new Intent(captureIntent);
                i.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
                i.setPackage(packageName);
                i.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                cameraIntents.add(i);

            }
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("image/*");
            Intent chooserIntent = Intent.createChooser(i, "选择图片");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));
            startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (!web.canGoBack()) {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isActivityEntrance = 0;
        if (web != null) {
            web.removeAllViews();
            // in android 5.1(sdk:21) we should invoke this to avoid memory leak
            // see (https://coolpers.github.io/webview/memory/leak/2015/07/16/
            // android-5.1-webview-memory-leak.html)
            ((ViewGroup) web.getParent()).removeView(web);
            web.setTag(null);
            web.clearHistory();
            web.destroy();
            web = null;
        }
    }

    /**
     * 清理缓存
     *
     * @param dir
     * @param numDays
     * @return
     */
    private int clearCacheFolder(File dir, long numDays) {
        int deletedFiles = 0;
        if (dir != null && dir.isDirectory()) {
            try {
                for (File child : dir.listFiles()) {
                    if (child.isDirectory()) {
                        deletedFiles += clearCacheFolder(child, numDays);
                    }
                    if (child.lastModified() < numDays) {
                        if (child.delete()) {
                            deletedFiles++;
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return deletedFiles;
    }

    /**
     * 清除历史记录
     */
    void clearHistory() {
        if (web != null) {
            web.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (web != null) {
                        web.clearHistory();
                    }
                }
            }, 1000);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    /**
     * 分享
     */
    private void showshear() {
        //开启自定义分享页面
//        Bundle bundle = new Bundle();
//        bundle.putSerializable("Hot", bannerEntity);
//        ActivityUtil.next(this, MyShareActivity.class, bundle);

        String[] mPermissionList = new String[]{
                android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
//                    Manifest.permission.ACCESS_FINE_LOCATION,
//                    Manifest.permission.CALL_PHONE,
//                    Manifest.permission.READ_LOGS,
//                    Manifest.permission.READ_PHONE_STATE,
//                    Manifest.permission.READ_EXTERNAL_STORAGE,
//                    Manifest.permission.SET_DEBUG_APP,
//                    Manifest.permission.SYSTEM_ALERT_WINDOW,
//                    Manifest.permission.GET_ACCOUNTS,
//                    Manifest.permission.WRITE_APN_SETTINGS
        };
        PermissionHelper.requestMultiPermissions(this,PERMISSION_SHARE,"分享需要权限《存储》，请授权",permissionResult,mPermissionList);
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionHelper.requestPermissionsResult(requestCode,permissions,grantResults,permissionResult);
    }
    PermissionHelper.PermissionResult permissionResult=new PermissionHelper.PermissionResult() {
        @Override
        public void onPermissionGranted(int requestCode) {
            switch (requestCode){
                case PERMISSION_SHARE:
                    break;
            }
        }

        @Override
        public void onPermissionDenied(int requestCode, String... noPermissions) {
            switch (requestCode){
                case PERMISSION_SHARE:
                    PermissionHelper.permissionDined(MyWebActivity.this,"您拒绝了《存储》权限，无法使用分享功能，若想继续分享，请手动开启","您拒绝了《存储》权限，无法使用分享功能.");
                    break;
//                case PERMISSION_SHARE:
//                    String des="";
//                    for(String permission:noPermissions){
//                        if(permission.equals(Manifest.permission.CALL_PHONE)){
//                            des+="<拨打电话>";
//                        }
//                        if(permission.equals(Manifest.permission.CAMERA)){
//                            des+="<相机>";
//                        }
//                    }
//                    PermissionHelper.permissionDined(getActivity(),"您拒绝了"+des+"权限，无法正常使用此功能模块，若想继续使用，请手动开启","您拒绝了"+des+"权限，无法正常使用此功能");
//                    break;
            }
        }
    };
}
